package controller;

import java.util.HashSet;
import java.util.Set;

import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import domain.Address;
import domain.Contact;
import domain.ContactGroup;
import domain.POJOFactory;
import domain.PhoneNumber;

public class RedirectionController {

	public String redirectToAdd() {
		return "ajouter";
	}

	public String redirectToListContact() {
		return "lister";
	}

	public String redirectToModify() {
		return "modifier";
	}

	public String redirectToListInfosContact() {
		return "listInfos";
	}

	public String feedDataBase() {
		ApplicationContext context = WebApplicationContextUtils
				.getWebApplicationContext((ServletContext) FacesContext
						.getCurrentInstance().getExternalContext().getContext());
		domain.IContact contact1 = (domain.IContact) context
				.getBean("myContact1");
		domain.IContact contact2 = (domain.IContact) context
				.getBean("myContact2");
		domain.ContactGroup cg1 = (domain.ContactGroup) context
				.getBean("contactGroupTravail");

		domain.IDAOContact daoContact = (domain.IDAOContact) context
				.getBean("DaoContactBean");
		domain.DAOContactGroup daoContactGroup = (domain.DAOContactGroup) context
				.getBean("DaoContactGroupBean");
		try {
			daoContactGroup.addContactGroup(cg1);
			daoContact.addContact(contact1);
			daoContact.addContact(contact2);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "ok";
	}

	public String testCache(){
		ApplicationContext context = WebApplicationContextUtils
				.getWebApplicationContext((ServletContext) FacesContext
						.getCurrentInstance().getExternalContext().getContext());
		domain.DAOContact daoContact = (domain.DAOContact) context
				.getBean("DaoContactBean");
		POJOFactory facto = (domain.POJOFactory) context.getBean("PojoFactory");
		for (int i=0;i<60;i++){
			Address address = facto.createNewAddressInstance("rue du mal", "cite de la peur", "75013", "Paris");
			Contact c = null;
			Set<ContactGroup> books = new HashSet<ContactGroup>();
			Set<PhoneNumber> profiles = new HashSet<PhoneNumber>();
			books.add((domain.ContactGroup) context.getBean("contactGroupTravail"));
			profiles.add(facto.createNewPhoneNumberInstance("homephone", "0144584621", c));
			c = facto.createNewContactInstance("Ritchie", "Nithoo", "ritchie.nithoo", address, books, profiles);
			profiles.add(facto.createNewPhoneNumberInstance("homephone", "0144584621", c));
			daoContact.addContact(c);
		}
		
		for (int i=0 ; i<25;i++){
			daoContact.getHibernateTemplate().setCacheQueries(true);
			daoContact.getHibernateTemplate().find("from Contact");
			System.out.println("----------" + "TEST" + "----------");
		}
		return "Test du cache";
	}
}